package hot100.logos51To60;

import java.util.ArrayList;
import java.util.List;

/**
 * @author logos
 * date 2025/7/15 18:21
 * @version v1.0
 * @Package hot100.logos51To60
 */
public class logos59 {

    /**
     * 59. 括号生成
     * https://leetcode.cn/problems/generate-parentheses/description/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> ans = new ArrayList<>();
            dfs(n, 0, 0, new char[n * 2], ans);
            return ans;
        }

        private void dfs(int n, int i, int open, char[] path, List<String> ans) {
            if (i == n * 2) {
                ans.add(new String(path));
                return;
            }
            // 左括号的个数（open）小于总对数
            if (open < n) {
                path[i] = '(';
                dfs(n, i + 1, open + 1, path, ans);
            }
            // 右括号的个数小于左括号个数
            if (i - open < open) {
                path[i] = ')';
                dfs(n, i + 1, open, path, ans);
            }
        }
    }
}
